<template lang="pug">
div
  obj-single-select(
    :options="addresses",
    key="id",
    label="name",
    :placeholder="placeholder",
    :update="update",
    :selected.sync="address",
    :custom-label="customLabel",
    type="selected",
    @click="click",
    :loading="loading",
    :searchable="true",
  )
</template>

<script>
import { getAddresses } from '../../vuex/action'
import ObjSingleSelect from './objSingle'

export default {
  name: 'addressSelect',
  components: {
    ObjSingleSelect
  },
  vuex: {
    getters: {
    },
    actions: {
      getAddresses,
    }
  },
  props: ['address', 'user_id'],
  data () {
    return {
      loading: false,
      addresses: [],
    }
  },
  methods: {
    customLabel ({province, city, district, street, name, phone}) {
      if (this.helper.isAmountValid(name)) {
        return `${province}, ${city}, ${district}, ${street}, ${name}, ${phone}`
      }
      return '选择地址'
    },
    click (e) {
      if (e.target.parentElement.classList.toString() === 'multiselect__tags') {
        this.load()
      }
    },
    load () {
      catchError(async () => {
        this.loading = true
        if (this.user_id) {
          this.addresses = await this.getAddresses(this.user_id)
        }
        this.loading = false
      })
    },
    update(val) {
      this.address = val
    }
  },
  created () {
    this.load()
  },
  computed: {
    placeholder () {
      const result = _.find(this.addresses, ['id', _.get(this, 'address.id')])
      return result ? `${result.province}, ${result.city}, ${result.district}, ${result.street}, ${result.name}, ${result.phone}` : '选择地址'
    },
  },
  watch: {

  }
}
</script>

<style lang="sass" scoped>
</style>
